package com.jiangyg.mall.order.listener;

import com.jiangyg.mall.core.utils.Logger;
import com.jiangyg.mall.order.dto.SeckillOrderDTO;
import com.jiangyg.mall.order.service.OrderService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 类描述：秒杀订单队列监听
 *
 * @author jiangyg
 * @date 2022-12-18
 */
@Slf4j
@Component
@RabbitListener(bindings = @QueueBinding(
        value = @Queue(value = "seckill.order.queue", autoDelete = "false"),
        exchange = @Exchange(value = "order-event-exchange", type = ExchangeTypes.TOPIC)
))
public class SeckillOrderQueueListener {

    private final OrderService orderService;

    @Autowired
    public SeckillOrderQueueListener(OrderService orderService) {
        this.orderService = orderService;
    }

    @RabbitHandler
    public void listener(SeckillOrderDTO dto, Channel channel, Message message) throws IOException {
        try {
            Logger.info(log, () -> String.format("[秒杀订单监听]-准备开始创建秒杀订单[%d]……", dto.getOrderId()));
            this.orderService.seckill(dto);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception ex) {
            Logger.info(log, () -> String.format("[秒杀订单监听]-创建秒杀订单[%d]出错……", dto.getOrderId()), ex);
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }

}
